package com.mayikt.spike.produce;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SpikeCommodityProducer implements RabbitTemplate.ConfirmCallback {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendMsg(JSONObject jsonObject){
        String jsonStr = jsonObject.toJSONString();
        // 封装消息
        String messageId = jsonObject.getString("productToken").replace("-", "");
        Message message = MessageBuilder.withBody(jsonStr.getBytes()).setContentType(MessageProperties.CONTENT_TYPE_JSON)
                .setContentEncoding("utf-8").setMessageId(messageId).build();

        // 构建回调返回的数据（消息id）
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback(this);
        CorrelationData correlationData = new CorrelationData(jsonStr);
        rabbitTemplate.convertAndSend("modify_exchange_name","modifyRoutingKey",message,correlationData);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String messageId = correlationData.getId();
        log.info("消息id:{}",messageId);
        if (ack){
            log.info(">>>使用MQ消息确认机制确保消息一定投递到消息队列中");
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(messageId);
        this.sendMsg(jsonObject);
        log.info(">>>>使用mq消息确认机制投递到mq失败");
    }
}
